package com.mockapi.controller;

import com.mockapi.service.MockService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * Mock API控制器
 * 处理所有API请求
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class MockController {

    private final MockService mockService;

    /**
     * 处理所有HTTP方法的请求
     */
    @RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, 
                                           RequestMethod.DELETE, RequestMethod.PATCH, RequestMethod.HEAD, 
                                           RequestMethod.OPTIONS})
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MockService.MockResponse mockResponse = mockService.handleRequest(request);
        
        // 设置响应状态码
        response.setStatus(mockResponse.getStatusCode());
        
        // 设置响应头
        response.setContentType(mockResponse.getContentType());
        response.setCharacterEncoding("UTF-8");
        
        // 设置模板中定义的响应头
        if (mockResponse.getHeaders() != null) {
            for (Map.Entry<String, String> entry : mockResponse.getHeaders().entrySet()) {
                response.setHeader(entry.getKey(), entry.getValue());
            }
        }
        
        // 写入响应体
        if (mockResponse.getBody() != null && !mockResponse.getBody().isEmpty()) {
            response.getWriter().write(mockResponse.getBody());
        }
    }
} 